/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-06 15:05:44
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.controller;

import cn.afterturn.easypoi.cache.manager.POICacheManager;
import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ExcelToHtmlParams;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyApplyFireAddBean;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyApplyFireEditBean;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyApplyFireListBean;
import com.joysuch.wwyt.bp.bean.safetyworkcert.BpWorkSafetyCertSearchBean;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyCert;
import com.joysuch.wwyt.bp.service.BpWorkSafetyApplyFireService;
import com.joysuch.wwyt.bp.service.BpWorkSafetyCertService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.risk.repository.RiskEvaluationPlanDao;
import com.joysuch.wwyt.risk.repository.RiskPointDao;
import com.joysuch.wwyt.risk.service.RiskEvaluationPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/bp/work-safety-apply-donghuo")
@Api(tags = "/bp/work-safety-apply-donghuo 动火作业")
public class BpWorkSafetyApplyFireController {

    private static final Logger logger = LoggerFactory.getLogger(BpWorkSafetyApplyFireController.class);

    @Autowired
    private RiskEvaluationPlanDao dao;
    @Autowired
    private RiskPointDao pointDao;
    @Autowired
    private RiskEvaluationPlanService riskEvaluationPlanService;
    @Autowired
    private BpWorkSafetyApplyFireService bpWorkSafetyApplyFireService;
    @Autowired
    private BpWorkSafetyCertService bpWorkSafetyCertService;

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ApiOperation("动火-添加")
    public Object add(@Valid @RequestBody BpWorkSafetyApplyFireAddBean entity) throws Exception {
//        try {
//            // bpWorkSafetyApplyFireService.add(entity);
        BpWorkSafetyCert cert = bpWorkSafetyCertService.addFireCert(entity);
        return ResultBean.success(cert);
//        } catch (Exception e) {
//            logger.error("创建失败", e);
//            return ResultBean.fail(101, "创建失败");
//        }
    }

    @RequestMapping("update")
    public Object update(@Valid @RequestBody BpWorkSafetyApplyFireAddBean entity) throws Exception {
//        try {
        if (entity.getId() == null) {
            return ResultBean.fail(102, "未指定主键");
        }
        // bpWorkSafetyApplyFireService.update(entity);
        BpWorkSafetyCert cert = bpWorkSafetyCertService.updateFireCert(entity);
        return ResultBean.success(cert);
//        } catch (Exception e) {
//            logger.error("更新失败：#" + entity.getId(), e);
//            return ResultBean.fail(101, "更新失败");
//        }
    }

    @RequestMapping("page")
    public Object page(Pageable page, BpWorkSafetyCertSearchBean condition) {
        try {
            // Page<BpWorkSafetyApplyFireListBean> data = bpWorkSafetyApplyFireService.findByPage(page, condition);
            Page<BpWorkSafetyApplyFireListBean> data = bpWorkSafetyCertService.findByPageFire(page, condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @GetMapping("get")
    public Object getById(Long id) {
        try {
            Assert.notNull(id, "id不能为空");
            // BpWorkSafetyApplyFireEditBean data = bpWorkSafetyApplyFireService.findDetailById(id);
            BpWorkSafetyApplyFireEditBean data = bpWorkSafetyCertService.findDetailByIdFire(id);
            return ResultBean.success(data);
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @RequestMapping("delete")
    public Object delete(Long id) {
        try {
            bpWorkSafetyCertService.delete(id);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }


    /**
     * 07 版本EXCEL预览
     */
    @RequestMapping("07")
    public void toHtmlOf07Base(Pageable page, HttpServletResponse response) throws IOException, Exception {
        // riskEvaluationPlanService.list(page, null);

        ExcelToHtmlParams params = new ExcelToHtmlParams(WorkbookFactory.create(POICacheManager.getFile("D:/excel/风险控制数据.xlsx")));
        response.getOutputStream().write(ExcelXorHtmlUtil.excelToHtml(params).getBytes());
        System.out.println("这是打印" + params);
    }


    //作业证导出
    @RequestMapping("apply-donghuo-list")
    public void SimpleWordExport(HttpServletRequest request, HttpServletResponse response, Long id) throws IOException {
        Map<String, Object> map = bpWorkSafetyCertService.getFileSafetyMap(id);
//        FileInputStream oo = new FileInputStream(new File("F:"+File.separator+"test"+File.separator+"1737437f3eacdb4e2ce4a10391f0a1e.png"));
//        byte[] abc = ByteStreams.toByteArray(oo);
//        ImageEntity imageEntity = new ImageEntity(abc, 50, 50);
//        map.put("@test",imageEntity);
        try {
            InputStream stream = BpWorkSafetyApplyFireController.class.getClassLoader().getResourceAsStream("template/DH.docx");
            //XWPFDocument xwpfDocument = new XWPFDocument();
            byte[] bytes = new byte[0];
            bytes = new byte[stream.available()];
            stream.read(bytes);
//                String str = new String(bytes);
//                System.out.println("这是转化出来的====="+str);
            XWPFDocument doc = WordExportUtil.exportWord07(
                    "template/DH.docx", map);
            FileOutputStream fos = new FileOutputStream("F:" + File.separator + "test" + File.separator + "DH.docx");
            doc.write(fos);
            fos.close();
            String image = "F:" + File.separator + "test" + File.separator + "DH.docx";
            File imageFile;
            imageFile = new File(image);
            response.setContentType(getContentType(imageFile));
            // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            // 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
            String filename = "DH.docx";
            String agent = request.getHeader("User-Agent");
            if (agent.contains("MSIE")) {
                // IE浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+", " ");
            } else {
                // 其它浏览器
                filename = URLEncoder.encode(filename, "utf-8");
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            if (imageFile.exists()) {
                byte[] cache = new byte[2048];
                int len = 0;
                FileInputStream fis = new FileInputStream(imageFile);
                while ((len = fis.read(cache)) != -1) {
                    response.getOutputStream().write(cache, 0, len);
                }
                fis.close();
                response.getOutputStream().flush();
            } else {
                response.setStatus(404);
                response.getOutputStream().flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private String getContentType(File imageFile) {
        return "multipart/form-data";
    }
/*  map.put("applyDepartName", data.getApplyDepartName());//申请单位
        map.put("applyUserName", data.getApplyUserName());//申请人
        map.put("code", data.getCode());//作业证编号
        map.put("stateName", data.getStateName());//状态
        map.put("workLevelName", data.getWorkLevelName());//作业级别
        map.put("opFireMethodName", data.getOpFireMethodName());//动火方式
        map.put("opFireContent", data.getOpFireContent());//动火内容
        map.put("locationCoords", data.getLocationCoords());//动火区域
        map.put("startTime", data.getStartTime());//动火开始时间
        map.put("endTime", data.getEndTime());//动火结束时间
        map.put("riskDistrictName", data.getRiskDistrictName());//所属风险区域
        map.put("username", data.getProductionDepartResponsibleUserName());//生产单位负责人
        map.put("responsibleUserName", data.getOpFireJobResponsibleUserName());//动火作业负责人
        map.put("aditUserName", data.getOpFireFirstAuditUserName());//动火初审人
        map.put("opFireUserName", data.getOpFireMonitorUserName());//监火人
        map.put("opUserName", data.getOpFireEducationUserName());//实施安全教育人
        map.put("riskLevelName", data.getRiskLevelName());//作业风险评估
        map.put("attachment", data.getAttachment().getName());//附件
        map.put("dangerRecoganize", data.getDangerRecoganize());//危害辨识
        map.put("needEletricityApplySheet", data.getNeedEletricityApplySheet());//是否需要电子申请单
        map.put("workToolName", data.getWorkToolName());//工具名称

        map.put("confirmUserName", data.getSafetyMethods().get(0).getConfirmUserName());//确定人
        map.put("editUserName", data.getEditUserName());//编制人
        if(data.getPeople().size() >0){
            List<BpWorkSafetyApplyUserDetailBean> people = data.getPeople();
            for (BpWorkSafetyApplyUserDetailBean person : people) {
                Map<String, String> maps = new HashMap<String, String>();
                maps.put("id", person.getId());//序号
                maps.put("opUserName",person.getOpUserName());//动火人员
                maps.put("userType", person.getUserType());//身份
                maps.put("departName", person.getDepartName());//所属单位
                maps.put("certName", person.getCertName());//证书名称
                listMap.add(maps);
            }
            map.put("m", listMap);
        }*/

}
